<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Action\OrderDelivery;
use App\Admin\Extensions\Action\PageJumpAction;
use App\Admin\Filters\TimestampBetween;
use App\Http\Services\OrderService;
use App\Http\Traits\GlobalConstant;
use App\Models\Order;
use App\Util\Helper;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class OrderController extends BaseController
{

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('订单列表')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('订单详情')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑订单')
            ->description(' ')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增作物')
            ->description('新增作物')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1 / 3, function ($filter) {
                $filter->like('userInfo.mobile', '手机号');
                $filter->equal('order_sn', '订单编号');

            });
            $filter->column(1 / 3, function ($filter) {
                $filter->like('goodsInfo.name', '商品名称');
                $payTypeArr = array_merge(GlobalConstant::getPayTypeMap(), ['exchange' => '认养支付']);
                $filter->equal('pay_type', '付款方式')->select($payTypeArr);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('status', '订单状态')->select([1 => '进行中', 2 => '已发货']);
                $filter->use(new TimestampBetween('created_at', __('下单时间')))->datetime();
            });
        });
//
        $grid->model()->where('status', '>=', 1)->where('refund_status', 0)->orderBy('id', 'desc');
//        $grid->column('id', '订单ID')->sortable();
        $grid->column('order_sn', '订单编号');
        $grid->column('userInfo.nickname', '用户')->sortable();
        $grid->column('goodsInfo.name', '商品');
        $grid->column('price', '价格')->display(function ($v) {
            return Helper::centToYuan($v);
        });
        $grid->column('price_rebate', '折扣')->display(function ($v) {
            if ($v > 0 && $v < 1) {
                return ($v * 10) . '折';
            }
            if ($v <= 0) {
                return '';
            }
            if ($v > 1) {
                return sprintf("%.2f", $v);
            }
        });
        $grid->column('rebate_desc', '优惠券金额')->display(function ($v) {
            if (empty($v)) {
                return "0.00";
            }
            return sprintf("%.2f", $v['coupon_money']);
        });
        $grid->column('price_real', '实际售价')->display(function ($v) {
            return Helper::centToYuan($v);
        });
        $grid->column('total_num', '数量');
        $grid->column('price_total', '总价')->display(function ($v) {
            return Helper::centToYuan($v);
        });
        $grid->column('pay_total', '实付金额')->display(function ($v) {
            return Helper::centToYuan($v);
        });
        $grid->column('express_name', '物流');
        $grid->column('express_number', '物流单号');
        $grid->column('status', '状态')->display(function ($v) {
            if ($v == 0) {
                return '待付款';
            }
            if ($v == 1) {
                return '进行中';
            }
            if ($v == -1) {
                return '已取消';
            }
            if ($v == 2) {
                return '已完成';
            }
        })->label([-1 => 'warning', 0 => 'primary', 1 => 'info', 2 => 'success']);
        $grid->column('pay_type', '支付方式')->display(function ($v) {
            if ($v == 'exchange') {
                return '认养支付';
            } else {
                return GlobalConstant::getPayTypeMap($v);
            }

        });
//        $grid->column('pick_up_num', '已提货数量');
        $grid->column('pay_at', '支付时间');
        $grid->column('created_at', '下单时间');
        $grid->column('delivery_at', '发货时间');
        $grid->disableCreateButton();
        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
//            $actions->add(new OrderPick());
            $actions->add(new PageJumpAction('详情', '/admin/order/' . $actions->getKey()));
            $actions->add(new OrderDelivery());

        });
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->expandFilter();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));
        $show->field('order_sn', '订单编号');
        $show->field('userInfo.nickname', '用户');
        $show->field('price', '售价')->as(function ($v) {
            return Helper::centToYuan($v);
        });
        $show->field('price_rebate', '折扣')->as(function ($v) {
            if ($v > 0 && $v < 1) {
                return ($v * 10) . '折';
            }
            if ($v <= 0) {
                return '';
            }
            if ($v > 1) {
                return sprintf("%.2f", $v);
            }
        });
        $show->field('price_real', '最终价')->as(function ($v) {
            return Helper::centToYuan($v);
        });
        $show->field('total_num', '购买数量');
        $show->field('price_total', '商品总价')->as(function ($v) {
            return Helper::centToYuan($v);
        });
        $show->field('rebate_desc', '优惠明显')->json();
        $show->field('pay_total', '实付总价')->as(function ($v) {
            return Helper::centToYuan($v);
        });
        $show->field('status', '状态')->as(function (){
            return OrderService::showOrderStatusTip($this);
        });
        $show->field('pay_type', '支付类型')->as(function ($v) {
            if ($v == 'exchange') {
                return '认养支付';
            } else {
                return GlobalConstant::getPayTypeMap($v);
            }
        });
//        $show->field('pay_identifier', '支付回执号');
//        $show->field('pick_up_num', '已提货数量');
        $show->field('pay_at', '支付时间');
//        $show->field('cancel_at', '取消时间')->as(function ($v) {
//            return $v == 0 ? '' : date('Y-m-d H:i:s', $v);
//        });
        $show->field('address', '收货地址')->as(function ($v) {
            $arr = explode('@', $v);
            return implode(' ', $arr);
        });
        $show->field('goods_snap', '商品快照')->as(function ($arr) {
            $arrKey = ['title' => '商品名称', 'type' => '商品分类', 'tag' => '标签', 'output' => '产量', 'reap_at' => '收获时间'];
            $html   = '';
            foreach ($arr as $key => $item) {
                if (!array_key_exists($key, $arrKey)) {
                    continue;
                }
                $html .= $arrKey[$key] . ' : ' . $item . '<br>';
            }
            return $html;
        })->unescape();
        $show->field('created_at', '下单时间');
        $show->panel()
            ->tools(function ($tools) {
                $tools->disableDelete();
                $tools->disableEdit();
            });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = 0)
    {
        $form = new Form(new Order());

        $form->tools(function (Form\Tools $tools) {
            // 去掉`删除`按钮
            $tools->disableDelete();
            $tools->disableView();
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }


}
